<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="订单号" prop="outTradeNo	">
        <el-input
          v-model="queryParams.outTradeNo	"
          placeholder="请输入订单号	"
          clearable
          style="width: 200px"
        />
      </el-form-item>
       <el-form-item label="微信支付订单号	" prop="tradeNo	">
        <el-input
          v-model="queryParams.tradeNo	"
          placeholder="请输入微信支付订单号	"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="roleList"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户ID" prop="userId" width="120" />
      <el-table-column label="商户订单号" prop="outTradeNo" :show-overflow-tooltip="true" />
      <el-table-column label="支付订单号" prop="tradeNo" :show-overflow-tooltip="true" />
      <el-table-column label="支付金额" prop="amount" width="100" />
      <el-table-column label="退款状态" prop="refundStatus" width="100">
        <template #default="{ row }">
          <span :style="getRefundStatusStyle(row.refundStatus)">
            {{ getRefundStatusText(row.refundStatus) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" prop="payStatus" width="120">
        <template #default="{ row }">
          <span :style="getPayStatusStyle(row.payStatus)">
            {{ getPayStatusText(row.payStatus) }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="剩余可退金额" prop="remainingRefundAmount" width="120" />
      <el-table-column label="累计退款次数" prop="refundCount" width="120" />

      <el-table-column label="操作" align="center" width="240">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            icon="Money"
            :disabled="row.remainingRefundAmount <= 0"
            @click="openRefundDialog(row)"
          >
            退款
          </el-button>

          <el-button
            link
            type="primary"
            icon="Search"
            @click="handleQuery(row)"
          >
            查询
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />

    <!-- 退款弹窗 -->
    <el-dialog
      v-model="refundDialog.visible"
      title="退款操作"
      width="500px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单号">{{ refundDialog.data.outTradeNo }}</el-descriptions-item>
        <el-descriptions-item label="支付金额">¥{{ refundDialog.data.amount }}</el-descriptions-item>
        <el-descriptions-item label="剩余可退金额">¥{{ refundDialog.data.remainingRefundAmount }}</el-descriptions-item>
      </el-descriptions>

      <el-form :model="refundForm" label-width="100px" class="mt-3" ref="refundFormRef">
        <el-form-item label="退款金额" prop="refundAmount" :rules="refundAmountRule">
          <el-input v-model="refundForm.refundAmount" placeholder="请输入退款金额" />
        </el-form-item>
        <el-form-item label="退款原因" prop="reason" :rules="refundReasonRule">
          <el-input v-model="refundForm.reason" placeholder="请输入退款原因(不超过80字)" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="refundDialog.visible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="refundDialog.loading"
          @click="submitRefund"
        >
          确认退款
        </el-button>
      </template>
    </el-dialog>

    <!-- 查询结果弹窗 -->
<el-dialog
  v-model="refundQueryDialog.visible"
  title="退款查询结果"
  width="700px"
>
  <el-scrollbar height="400px">
    <pre style="background: #f8f8f8; padding: 15px; border-radius: 6px; white-space: pre-wrap;">
{{ JSON.stringify(refundQueryDialog.data, null, 2) }}
    </pre>
  </el-scrollbar>

  <template #footer>
    <el-button @click="refundQueryDialog.visible = false">关闭</el-button>
  </template>
</el-dialog>

  </div>
</template>

<script setup name="Role">
import { listRole, refundOrder ,selectRefundNo} from "@/api/min-app/order";
import { ElMessage, ElMessageBox } from "element-plus";

const roleList = ref([]);
const loading = ref(true);
const total = ref(0);
const showSearch = ref(true);

const data = reactive({
  queryParams: {
    page: 1,
    size: 10,
    outTradeNo: '',
    tradeNo: '',
  },
});

const { queryParams } = toRefs(data);
const refundQueryDialog = reactive({
  visible: false,
  data: {},
});


const refundStatusMap = {
  0: "退款中",
  1: "退款成功",
  2: "退款失败",
  3: "未退款",
};
const payStatusMap = {
  0: "待支付",
  1: "支付成功",
  2: "支付失败",
  3: "支付超时",
  4: "已关闭",
};
const getRefundStatusText = (val) => refundStatusMap[val] || "未知";
const getPayStatusText = (val) => payStatusMap[val] || "未知";

// 状态样式
const getPayStatusStyle = (status) => {
  switch (status) {
    case 1:
      return { color: "#67C23A", fontWeight: "bold" }; // 成功绿色
    case 2:
    case 7:
      return { color: "#F56C6C", fontWeight: "bold" }; // 失败红
    case 5:
    case 6:
      return { color: "#E6A23C", fontWeight: "bold" }; // 部分退款橙
    case 8:
      return { color: "#909399" }; // 已关闭灰
    default:
      return { color: "#606266" };
  }
};
const getRefundStatusStyle = (status) => {
  switch (status) {
    case 1:
      return { color: "#67C23A", fontWeight: "bold" };
    case 0:
      return { color: "#E6A23C", fontWeight: "bold" };
    case 2:
      return { color: "#F56C6C", fontWeight: "bold" };
    default:
      return { color: "#909399" };
  }
};

// 请求锁
let loadingLock = false;

// 获取列表
function getList() {
  if (loadingLock) return;
  loading.value = true;
  loadingLock = true;

  const params = {
    page: queryParams.value.page,
    size: queryParams.value.size,
    tradeNo: queryParams.value.tradeNo || "",
    outTradeNo: queryParams.value.outTradeNo || "",
  };

  listRole(params)
    .then((res) => {
      roleList.value = res.data.records || [];
      total.value = Number(res.data.total) || 0;
    })
    .catch(() => ElMessage.error("加载失败，请稍后重试"))
    .finally(() => {
      loading.value = false;
      loadingLock = false;
    });
}

// 重置搜索
function resetQuery() {
  queryParams.value = { page: 1, size: 10 };
  getList();
}

// 退款弹窗
const refundDialog = reactive({
  visible: false,
  data: {},
  loading: false,
});
const refundFormRef = ref(null);
const refundForm = reactive({
  refundAmount: "",
  reason: "",
});
const refundAmountRule = [
  { required: true, message: "请输入退款金额", trigger: "blur" },
  {
    validator: (rule, value, callback) => {
      if (!/^[0-9]+(\.[0-9]{1,2})?$/.test(value)) callback(new Error("格式错误"));
      else callback();
    },
    trigger: "blur",
  },
];
const refundReasonRule = [
  { required: true, message: "请输入退款原因", trigger: "blur" },
  { min: 1, max: 80, message: "退款原因1-80字", trigger: "blur" },
];

function openRefundDialog(row) {
  refundDialog.data = row;
  refundForm.refundAmount = "";
  refundForm.reason = "";
  refundDialog.visible = true;
}

function submitRefund() {
  refundFormRef.value.validate((valid) => {
    if (!valid) return;
    const row = refundDialog.data;
    const refundAmount = parseFloat(refundForm.refundAmount);
    if (refundAmount > row.remainingRefundAmount) {
      return ElMessage.error("退款金额不能超过剩余可退金额");
    }

    refundDialog.loading = true;
    refundOrder({
      outTradeNo: row.outTradeNo,
      refundAmount,
      reason: refundForm.reason,
    })
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success("退款申请已提交");
          refundDialog.visible = false;
          getList();
        } else {
          ElMessage.error(res.msg || "退款失败");
        }
      })
      .catch(() => ElMessage.error("退款请求失败，请稍后重试"))
      .finally(() => (refundDialog.loading = false));
  });
}

// 查询状态
async function handleQuery(row) {
  try {
    const res = await selectRefundNo({
      outRefundNo: row.outRefundNo || row.outTradeNo,
    });
    if (res.code === 200) {
      // 打开弹窗展示原始数据
      refundQueryDialog.data = res.data;
      refundQueryDialog.visible = true;
    } else {
      ElMessage.error(res.msg || "查询失败");
    }
  } catch (e) {
    ElMessage.error("请求失败，请稍后重试");
  }
}




getList();
</script>

<style scoped>
.mt-3 {
  margin-top: 15px;
}
</style>
